package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bwie.mapper.ProdAttaMapper;
import com.bwie.pojo.ProdAtta;
import com.bwie.utils.R;
import com.bwie.vo.PageInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.Prod;
import com.bwie.mapper.ProdMapper;
import com.bwie.service.ProdService;
@Service
public class ProdServiceImpl extends ServiceImpl<ProdMapper, Prod> implements ProdService{
    @Autowired
    ProdMapper prodMapper;

    @Autowired
    ProdAttaMapper prodAttaMapper;

    @Override
    public R prodList(PageInfoVo pageInfoVo) {
        Page<Prod> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());
        Page<Prod> prodPage=prodMapper.getProdList(page,pageInfoVo);
        return R.OK(prodPage);
    }

    @Override
    public R addProdList(Prod prod) {
        Prod prod1 = prodMapper.selectOne(new QueryWrapper<Prod>().lambda().eq(Prod::getProdSpu, prod.getProdSpu()));
        if(prod1!=null){
            return R.ERROR(500,"已存在SPU");
        }
        prod.setCreateTime(new Date());
        save(prod);
        return R.OK();
    }

    @Override
    public R addProdAtta(ProdAtta prodAtta) {
//        ProdAtta prodAtta1 = prodAttaMapper.selectOne(new QueryWrapper<ProdAtta>().lambda().eq(ProdAtta::getProdId, prodAtta.getAttaId()));
        Prod prod = prodMapper.selectById(prodAtta.getProdId());
        if(prod==null){
            return R.ERROR(500,"商品不存在");
        }
        List<ProdAtta.AttaItem> attaList = prodAtta.getAttaList();
        ArrayList<String> strings = new ArrayList<>();
        for (ProdAtta.AttaItem attaItem : attaList) {

            strings.add(attaItem.getUrl());
        }
        String join = StringUtils.join(strings,"," );

        prodAtta.setAttaImages(join);
        prodAttaMapper.delete(new QueryWrapper<ProdAtta>().lambda().eq(ProdAtta::getProdId,prodAtta.getProdId()));
        prodAttaMapper.insert(prodAtta);
        return R.OK();
    }
}
